package org.jctc.els.modules.biz.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.jctc.els.modules.biz.entity.FileUtilAliOss;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 上传
 */
@RestController
public class UploadFileController {

    @Value("${oss.access-key}")
    private  String accessKeyId;

    @Value("${oss.secret-key}")
    private  String accessKeySecret ;

    @Value("${oss.bucket-name}")
    private  String pBbucket ;

    @Value("${oss.endpoint}")
    private  String pEndpoint ;

    @GetMapping("/pre/upload/image")
    public R getImageSignature(String fileCatalog, String dir, String fileSuffix) {
        FileUtilAliOss objFileUtil = new FileUtilAliOss();

        String accessId = accessKeyId;
        String accessKey = accessKeySecret;
        String bucket = pBbucket;
        String endpoint = pEndpoint;
        String host = "http://" + bucket + "." + endpoint;
        long max = ".jpg".equals(fileSuffix)|| ".gif".equals(fileSuffix)||".jpeg".equals(fileSuffix)||".png".equals(fileSuffix)? 524288000 : 512000;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 3600L * 24 * 365 * 10;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, max);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> params = new LinkedHashMap<String, String>();
            params.put("key", objFileUtil.calculateObjectName(fileCatalog, dir, fileSuffix, 32));
            params.put("policy", encodedPolicy);
            params.put("OSSAccessKeyId", accessId);
            params.put("success_action_status", "200");
            params.put("signature", postSignature);
            params.put("host", host);

            return R.data(params);
        } catch (Exception e) {
            return R.fail("上传失败！");
        }
    }

    /**
     * 上传视频
     * @param fileCatalog
     * @param dir
     * @param fileSuffix
     * @return
     */
    @GetMapping("/pre/upload/video")
    public R getSignature(String fileCatalog, String dir, String fileSuffix) {

        FileUtilAliOss objFileUtil = new FileUtilAliOss();

        String accessId = accessKeyId;
        String accessKey = accessKeySecret;
        String bucket = pBbucket;
        String endpoint = pEndpoint;
        String host = "http://" + bucket + "." + endpoint;
        long max = ".mp4".equals(fileSuffix)? 524288000 : 524288000;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 3600L * 24 * 365 * 10;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, max);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> params = new LinkedHashMap<String, String>();
            params.put("key", objFileUtil.calculateObjectName(fileCatalog, dir, fileSuffix, 32));
            params.put("policy", encodedPolicy);
            params.put("OSSAccessKeyId", accessId);
            params.put("success_action_status", "200");
            params.put("signature", postSignature);
            params.put("host", host);


			return R.data(params);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("上传失败！");
        }
    }

    /**
     * 上传音频
     * @param fileCatalog
     * @param dir
     * @param fileSuffix
     * @return
     */
    @GetMapping("/pre/upload/voice")
    public R getVoice(String fileCatalog,String dir,String fileSuffix){
        FileUtilAliOss objFileUtil=new FileUtilAliOss();
        String accessId=accessKeyId;
        String accessKey=accessKeySecret;
        String bucket=pBbucket;
        String endpoint=pEndpoint;
        String host= "http://" + bucket + "." + endpoint;
        long max=".mp3".equals(fileSuffix) ? 524288000 : 524288000;
        OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId, accessKey);
        try {
            long expireTime = 3600L * 24 * 365 * 10;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, max);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("UTF-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> params = new LinkedHashMap<String, String>();
            params.put("key", objFileUtil.calculateObjectName(fileCatalog, dir, fileSuffix, 32));
            params.put("policy", encodedPolicy);
            params.put("OSSAccessKeyId", accessId);
            params.put("success_action_status", "200");
            params.put("signature", postSignature);
            params.put("host", host);

			return R.data(params);
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("上传失败！");
        }
    }
    @DeleteMapping("/pre/delete/file")
    public R deleteFile(String objectName) {
        String accessId = accessKeyId;
        String accessKey = accessKeySecret;
        String bucket = pBbucket;
        String endpoint = pEndpoint;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        ossClient.deleteObject(bucket,objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
        return R.success("操作成功！");
    }

    /**
     * 访问阿里云私有资源
     * @param objectName
     * @return
     */
    @GetMapping("/pre/get/signature-url")
    public R getSignatureUrl(String objectName) {


//
//        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(pEndpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间为1小时。
        Long l = System.currentTimeMillis();
        Date expiration = new Date(l  + 3600 * 1000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(pBbucket, objectName, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();


//        Long l = System.currentTimeMillis();
//        Date expiration = new Date(l  + 3600 * 1000);
//        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(pBbucket, objectName, HttpMethod.GET);
//        // 设置过期时间。
//        request.setExpiration(expiration);
//        // 生成签名URL（HTTP GET请求）。
//        URL signedUrl = ossClient .generatePresignedUrl(request);
//
//        // 使用签名URL发送请求。
//        Map<String, String> customHeaders = new HashMap<String, String>();
//        // 添加GetObject请求头。
//        customHeaders.put("Range", "bytes=100-1000");
//        OSSObject object = ossClient.getObject(signedUrl,customHeaders);


        return R.data(url);
    }

}
